<template>
  <div class="login-container">
    <!-- 登录表单 -->
    <el-form
      class="login-form"
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      autocomplete="on"
      label-position="left"
    >
      <!-- 标题 -->
      <div class="title-container">
        <h3 class="title">天下会论坛管理系统</h3>
      </div>
      <!-- 标题end -->
      <!-- 用户名 -->
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          name="username"
          type="text"
          v-model="loginForm.username"
          autocomplete="on"
          placeholder="用户名"
          tabindex="1"
          @keyup.enter.native="handleLogin"
        />
      </el-form-item>
      <!-- 用户名end -->
      <!-- 密码 -->
      <el-tooltip
        v-model="capsTooltip"
        content="大写锁定已打开"
        placement="right"
        manual
      >
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            ref="password"
            name="password"
            :type="passwordType"
            v-model="loginForm.password"
            placeholder="密码"
            autocomplete="on"
            tabindex="2"
            @keyup.native="checkCapslock"
            @keyup.enter.native="handleLogin"
            @blur="capsTooltip = false"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
      </el-tooltip>
      <!-- 密码end -->
      <!-- 验证码 -->
      <div class="captcha-item">
        <el-form-item class="captcha-input" prop="captcha">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            ref="captchaInput"
            name="captcha"
            type="text"
            v-model="loginForm.captcha"
            placeholder="请输入验证码"
            autocomplete="on"
            tabindex="3"
            @keyup.enter.native="handleLogin"
          />
        </el-form-item>
        <div class="captcha" @click="getCaptcha()">
          <el-image class="image" :src="captchaImg" />
        </div>
      </div>
      <!-- 验证码end -->
      <!-- 登录按钮 -->
      <el-button
        style="width: 100%; margin-bottom: 30px"
        :loading="loading"
        type="primary"
        tabindex="4"
        @click.native.prevent="handleLogin"
        >立即登录</el-button
      >
      <!-- 登录按钮end -->
    </el-form>
    <!-- 登录表单end -->
  </div>
</template>

<script>
import { validUsername, validPassword, validCaptcha } from "@/utils/validate";
import { generateUUID } from "@/utils";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error("用户名长度为1-16个字符，包括中文/大小写字母/数字"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (!validPassword(value)) {
        callback(
          new Error("密码长度为6-16个字符，包括大小写字母/数字/特殊字符")
        );
      } else {
        callback();
      }
    };
    const validateCaptcha = (rule, value, callback) => {
      if (!validCaptcha(value)) {
        callback(new Error("验证码长度为5个字符，包括大小写字母/数字"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "admin",
        password: "123456",
        captcha: "12345",
        appId: generateUUID(),
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
        captcha: [
          { required: true, trigger: "blur", validator: validateCaptcha },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      captchaImg: "",
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    this.getCaptcha();
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  methods: {
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "text";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery,
              });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    // 刷新验证码
    getCaptcha() {
      const random = Math.random();
      this.captchaImg = `${process.env.VUE_APP_BASE_API}Api/Captcha/GetImageCaptcha?appId=${this.loginForm.appId}&v=${random}`;
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */
$bg: #283443;
$light_gray: #000000;
$cursor: #000000;
@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}
/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      // -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: #ffffff;
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$dark_gray: #889aa4;
$light_gray: #1890ff;

.login-container {
  width: 100%;
  height: 100%;
  background-image: url("../../static/BackGround.png");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  overflow: hidden;
  .login-form {
    width: 520px;
    padding: 35px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: #ffffff87;
    border: white 1px solid;
    box-shadow: 0 0 8px #eee;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title-container {
    position: relative;
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }
  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
.captcha-item {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  .captcha-input {
    flex: 2;
    margin-bottom: 0px;
  }
  .captcha {
    flex: 1;
    .image {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
